package com.boarsoft.boar.gateway.server.service;

import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.boarsoft.demo.gateway.server.entity.PocAccountReverseRequest;
import com.boarsoft.demo.gateway.server.entity.PocAccountTransferRequest;
import com.boarsoft.demo.gateway.server.service.PocAccountTransferService;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@Component("demoMocker")
public class DemoMocker implements PocAccountTransferService {
	
	@Autowired
	private Configuration config;

	@Override
	public boolean reverse(PocAccountReverseRequest transferRequest) {
		System.out.println("I am demo mocker for reverse.");
		String requestXML = getTemplateContent("transfer_request.ftl", transferRequest);
		System.out.println("transfer request = [" + requestXML + " ]");
		String responseXML = getTemplateContent("transfer_response.ftl", new HashMap<String,String>());
		System.out.println("transfer response = [" + responseXML + " ]");
		return true;
	}

	@Override
	public boolean transfer(PocAccountTransferRequest reverseRequest) {
		System.out.println("I am demo mocker for transfer.");
		String requestXML = getTemplateContent("reverse_request.ftl", reverseRequest);
		System.out.println("reverse request = [" + requestXML + " ]");
		String responseXML = getTemplateContent("reverse_response.ftl", new HashMap<String,String>());
		System.out.println("reverse response = [" + responseXML + " ]");
		return true;
	}
	
	private String getTemplateContent(String templateName, Object bean) {
		try {
			Map<String, String> dataModel = BeanUtils.describe(bean);
			Template template = config.getTemplate(templateName);
			StringWriter sw = new StringWriter();
			template.process(dataModel, sw);
			return sw.toString();
		} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | IOException | TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
	}

}
